package com.rpc.framework;

import com.rpc.protocol.http.HttpProtocol;
import com.rpc.register.RemoteMapRegister;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @Author:cxy
 * @Date:2021/1/24 19:57
 */
public class ProxyFactory<T> {

    public static <T> T getProxy(Class<T> insterfaceName){

        return insterfaceName.cast(Proxy.newProxyInstance(insterfaceName.getClassLoader(), new Class[]{insterfaceName}, (proxy, method, args) -> {

            //构造协议
            final Invocation invocation = new Invocation(insterfaceName.getName(), method.getName(), method.getParameterTypes(), args);

            //获取到服务列表
            final List<URL> urls = RemoteMapRegister.getServerUrls(insterfaceName.getName());
            final URL url = LoadBalance.random(urls);

            //发送请求
            final HttpProtocol protocol = new HttpProtocol();
            return protocol.send(url,invocation);

        }));


    }

}
